package com.huanlis.consumer.controller;

import com.huanlis.consumer.thread.AsyncThread;
import com.huanlis.consumer.thread.LocalCache;
import com.huanlis.consumer.util.LocalState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.LockSupport;

@Slf4j
@RestController
public class AsyncController {

    public static final String Url = "http://localhost:8002/hello/test/?id=";



    @GetMapping("/async")
    public ResponseEntity<String> testAsync(@RequestParam("id") Integer id) {
        log.info("收到请求：{}----{}", Thread.currentThread().getName(), id);
        LocalCache localCache = new LocalCache();
        localCache.setCache(new LocalState(Url, false, id, ""));
        AsyncThread asyncThread = new AsyncThread(Thread.currentThread(), localCache);
        asyncThread.setName("AsyncThread-"+id);
        asyncThread.start();
        LockSupport.park();
        if (!localCache.getCache().getSuccess()) {
            log.error("异步请求错误：{}----{}", Thread.currentThread().getName(), id);
            return ResponseEntity.badRequest().build();
        }
        localCache.clear();
        log.info("返回结果：{}----{}", Thread.currentThread().getName(), id);
        return ResponseEntity.ok(localCache.getCache().getResult());
    }

}
